package org.ws.kardex.servlets.inventory;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.users.User;
import java.io.IOException;
import java.util.LinkedList;
import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ws.kardex.gae.PMF;
import org.ws.kardex.model.*;
import org.ws.kardex.utils.Const;

/**
 *
 * @author gerardino
 */
public class Admin extends HttpServlet {

    private static final String P_INVENTORY_ID = "iid";
    private static final String P_INVENTORY_NAME = "iName";
    private static final String P_INVENTORY_USERS = "newUsers";
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        
        String user = UserServiceFactory.getUserService().getCurrentUser().getNickname();
        LinkedList<String> messages = new LinkedList<String>();
        PersistenceManager pm = PMF.pm;
        Key k = null;
        try{
          Long id = Long.parseLong(request.getParameter(P_INVENTORY_ID));
          k = KeyFactory.createKey(Inventory.class.getSimpleName(), id);
        } finally {
        }
        Inventory i = pm.getObjectById(Inventory.class, k);
        
        if (user.equals(i.getOwner())){
            String newName = request.getParameter(P_INVENTORY_NAME);
            if (newName != null){
                if (newName.length() < 4){
                    messages.add("Nombre inv&aacute;lido");
                } else {
                    i.setName(newName);
                }
            }
            String usersList = request.getParameter(P_INVENTORY_USERS);
            if (usersList != null && usersList.length() > 0){
                String[] users = usersList.split(";");
                for(String u : users){
                    u = u.trim();
                    i.getUsers().indexOf(u);
                    if (u.equals(i.getOwner())){
                        messages.add("No es posible agregar al propietario del inventario como usuario.");                          
                    } else if (i.getUsers().indexOf(u) == -1 ){
                        if (u.matches(Const.EMAIL_REGULAR_EXPRESSION)){
                            
                            User validatedUser = new User(u, "gmail.com");
                            
                            if (validatedUser != null){
                                i.getUsers().add(validatedUser.getNickname());
                            } 
                            
                            //i.getUsers().add(u);
                        } else {
                            messages.add("La expresi&oacute;n \""+ u + "\" no parece ser una direcci&oacute;n de correo v&aacute;lida.");
                        }
                    }
                }
            }


            request.setAttribute("i", i);
            request.setAttribute(Const.MESSAGE, messages);

            String target = "/Inventory/admin.jsp";
            request.getRequestDispatcher(target).forward(request, response);
        } else {
            String target = "/Products/list?iid=" + i.getId().getId();
            request.getRequestDispatcher(target).forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
